package com.artron.mediaartron.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.util.SparseArrayCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.GridLayout;

import com.artron.baselib.adapter.recyclerview.BaseViewHolder;
import com.artron.mediaartron.R;

public class GridFactoryView extends GridLayout {

    private int mCardViewCount = 1;
    private SparseArrayCompat<ViewGroup> mCardViewFactory;

    private RecyclerView.Adapter<BaseViewHolder> mAdapter;

    private OnItemClickListener mOnItemClickListener;

    //Item是否是CardView
    private boolean mIsItemCardView;
    private int mWidthPixels;

    private int mRowCount = 0;
    private int mColumnCount = 0;

    public GridFactoryView(Context context) {
        super(context);
    }

    public GridFactoryView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.GridFactoryView);
        mIsItemCardView = typedArray.getBoolean(R.styleable.GridFactoryView_isItemCardVIew, true);
        mCardViewCount = typedArray.getInteger(R.styleable.GridFactoryView_gridSize, 0);
        typedArray.recycle();
    }

    public GridFactoryView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {

        init();
        setContentViewRes();
        super.onFinishInflate();
    }

    private void init() {
        mWidthPixels = getContext().getResources().getDisplayMetrics().widthPixels;
    }


    public void setContentViewRes() {
        mCardViewCount = getRowCount() * getColumnCount();
        mCardViewFactory = new SparseArrayCompat<>();
        this.removeAllViews();

        if (mRowCount != 0) {
            setRowCount(mRowCount);
        }

        if (mColumnCount != 0) {
            setColumnCount(mColumnCount);
        }
        for (int i = 0; i < mCardViewCount; i++) {
            Spec rowSpec = GridLayout.spec(i / getColumnCount());
            int start = i % getColumnCount();
            int size = (i != 0 && i == mCardViewCount - 1 && mCardViewCount % getColumnCount() != 0) ? 2 : 1;
            Spec columnSpec = GridLayout.spec(start, size);
            LayoutParams params = new LayoutParams(rowSpec, columnSpec);
            ViewGroup contentView;

            if (mIsItemCardView) {
                contentView = new CardView(getContext());

                int[] attrs = new int[]{android.R.attr.selectableItemBackground};
                TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs);
                Drawable drawable = a.getDrawable(0);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    contentView.setForeground(drawable);
                } else {
                    contentView.setBackgroundResource(R.drawable.item_touch_bg);
                }
            } else {
                contentView = new FrameLayout(getContext());
            }

            int marginPx = dip2px(1);

            if (i % getColumnCount() == 0) {
                params.setMargins(0, marginPx, marginPx, marginPx);
            } else if (i % getColumnCount() == getColumnCount() - 1) {
                params.setMargins(marginPx, marginPx, 0, marginPx);
            } else {
                params.setMargins(marginPx, marginPx, marginPx, marginPx);
            }

            int contentViewWidth = mWidthPixels - dip2px(4);
            params.height = params.width = size == 1 && mCardViewCount != 1 ?
                    contentViewWidth / getColumnCount() : contentViewWidth / getColumnCount();

            mCardViewFactory.put(i, contentView);
            this.addView(contentView, params);

            setListener(contentView, i);

//            requestLayout();
        }
    }

    public void setAdapter(RecyclerView.Adapter<BaseViewHolder> adapter) {
        mAdapter = adapter;

        initItem();
    }

    private void initItem() {
        if (mAdapter != null) {
            for (int i = 0; i < mAdapter.getItemCount(); i++) {
                ViewGroup contentView = mCardViewFactory.get(i);

                int childCount = contentView.getChildCount();
                BaseViewHolder holder;
                if (childCount == 0) {
                    holder = mAdapter.onCreateViewHolder(contentView, mAdapter.getItemViewType(i));
                    contentView.addView(holder.getContentView(), holder.getContentView().getLayoutParams());
                    contentView.setTag(holder);
                } else {
                    holder = (BaseViewHolder) contentView.getTag();
                }
                mAdapter.onBindViewHolder(holder, i);
            }
        }
    }

    private void setListener(View contentView, final int position) {
        contentView.setClickable(true);
        contentView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(v, position);
                }
            }
        });

        contentView.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemLongClick(v, position);
                }
                return false;
            }
        });
    }

    @Override
    public void setRowCount(int rowCount) {
        setRowCount(rowCount, false);
    }

    @Override
    public void setColumnCount(int columnCount) {
        setColumnCount(columnCount, false);
    }

    public void setRowCount(int rowCount, boolean flag) {
        if (flag) {
            mRowCount = rowCount;
            setContentViewRes();
        }
        super.setRowCount(rowCount);
    }

    public void setColumnCount(int columnCount, boolean flag) {
        if (flag) {
            mColumnCount = columnCount;
            setContentViewRes();
        }
        super.setColumnCount(columnCount);
    }

    @Override
    public int getRowCount() {
        return mRowCount != 0 ? mRowCount : super.getRowCount();
    }

    public int getColumnCount() {
        return mColumnCount != 0 ? mColumnCount : super.getColumnCount();
    }

    public void setItemMargin(int left, int top, int right, int bottom) {
        for (int i = 0; i < mCardViewFactory.size(); i++) {
            ViewGroup itemView = mCardViewFactory.valueAt(i);
            MarginLayoutParams layoutParams = (MarginLayoutParams) itemView.getLayoutParams();
            layoutParams.setMargins(left, top, right, bottom);
        }
    }


    public interface OnItemClickListener {
        void onItemClick(View view, int postion);

        void onItemLongClick(View view, int postion);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dip2px(float dpValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    private int px2dip(float pxValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}
